<template>
  <div id="loginPage" class="full">
    <div class="main">
      <!-- 左侧图片-->
      <div class="main-left">
        <el-image :src="LOGO_LEFT" class="full" />
      </div>
      <el-tabs
        class="login-tabs"
        type="border-card"
        @tab-click="handleTabClick"
      >
        <el-tab-pane v-for="item in PaneEnum" :key="item" :label="item">
          <!-- logo -->
          <div class="logo">
            <el-image :src="LOGO" />
            <span>云选购物</span>
          </div>
          <!-- 表单 -->
          <el-form
            v-if="item === PaneEnum.USERNAME"
            ref="loginRef"
            :model="loginData"
            :rules="loginRules"
            label-width="auto"
            style="padding: 10px"
          >
            <el-row :gutter="20">
              <el-col>
                <el-form-item label="账号" prop="username">
                  <el-input
                    v-model="loginData.username"
                    placeholder="请输入账号"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="密码" prop="password">
                  <el-input
                    v-model="loginData.password"
                    placeholder="请输入密码"
                    show-password
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="验证码" prop="captchaCode">
                  <captcha-input @get:captcha:data="handleCaptchaData" />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="用户类型" prop="typeNum">
                  <el-select
                    v-model="loginData.userType"
                    placeholder="请选择用户类型"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col>
                <el-button
                  style="width: 50%"
                  type="primary"
                  @click="loginSubmit"
                  >提 交
                </el-button>
              </el-col>
            </el-row>
          </el-form>
          <!-- 表单 -->
          <el-form
            v-else-if="item === PaneEnum.EMAIL"
            ref="emailLoginRef"
            :model="emailLoginDTO"
            :rules="emailLoginRules"
            :size="'large'"
            label-width="auto"
            style="padding: 10px"
          >
            <el-row :gutter="20">
              <el-col>
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="emailLoginDTO.email"
                    placeholder="请输入邮箱"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="验证码" prop="captchaCode">
                  <el-input
                    v-model="emailLoginDTO.captchaCode"
                    placeholder="请输入邮箱验证码"
                    @keyup.enter="emailLoginSubmit"
                  >
                    <template #append>
                      <el-button
                        :disabled="emailCountdown !== 60"
                        style="width: 150px"
                        @click="sendEmailCode"
                        >{{ emailSubText }}
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col>
                <el-button
                  style="width: 50%"
                  type="success"
                  @click="emailLoginSubmit"
                  >提 交
                </el-button>
              </el-col>
            </el-row>
          </el-form>
          <!-- 表单 -->
          <el-form
            v-else
            ref="phoneLoginRef"
            :model="phoneLoginDTO"
            :rules="phoneLoginRules"
            :size="'large'"
            label-width="auto"
            style="padding: 10px"
          >
            <el-row :gutter="20">
              <el-col>
                <el-form-item label="手机号" prop="phone">
                  <el-input
                    v-model="phoneLoginDTO.phone"
                    clearable
                    placeholder="请输入手机号"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="验证码" prop="captchaCode">
                  <el-input
                    v-model="phoneLoginDTO.captchaCode"
                    clearable
                    placeholder="请输入验证码"
                    @keyup.enter="phoneLoginSubmit"
                  >
                    <template #append>
                      <el-button
                        :disabled="phoneCountdown !== 60"
                        style="width: 150px"
                        @click="sendPhoneCode"
                        >{{ phoneSubText }}
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col>
                <el-button
                  style="width: 50%"
                  type="success"
                  @click="phoneLoginSubmit"
                  >提 交
                </el-button>
              </el-col>
            </el-row>
          </el-form>
          <el-link class="link" @click="openForget">忘记密码</el-link>
          <el-popover placement="bottom" trigger="hover" width="210">
            <template #reference>
              <el-link class="link">还没账号？立即注册</el-link>
            </template>
            <el-button text type="primary" @click="toRegister('user')"
              >用户注册
            </el-button>
            <el-button text type="primary" @click="toRegister('business')"
              >商家注册
            </el-button>
          </el-popover>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- ICP备案 -->
    <div class="icp-info">
      <el-space :size="'large'">
        <span>Copyright © 2024 阿良</span>
        <span>粤ICP备2024179481号</span>
      </el-space>
    </div>
  </div>
  <!-- 修改密码弹窗-->
  <el-dialog
    v-model="forgetVisible"
    center
    destroy-on-close
    :show-close="false"
    width="35%"
    title="忘记密码"
  >
    <!-- 滚动 -->
    <el-scrollbar max-height="60vh">
      <!-- 导航条-->
      <el-steps
        :active="active"
        align-center
        class="main-steps"
        finish-status="success"
        process-status="finish"
      >
        <el-step title="确认账号" />
        <el-step title="验证信息" />
        <el-step title="修改密码" />
      </el-steps>

      <div style="margin: 0 20px">
        <!-- 步骤1 -->
        <el-form
          v-show="active === 0"
          ref="registerRef"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="账号" prop="username">
                <el-input clearable placeholder="请输入账号" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="验证码" prop="captchaCode">
                <captcha-input
                  :time-limit-flag="false"
                  @get:captcha:data="handleCaptchaData"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 步骤2-->
        <el-form
          v-if="active === 1"
          ref="phoneLoginRef"
          :model="phoneLoginDTO"
          :rules="phoneLoginRules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="phoneLoginDTO.phone"
                  clearable
                  placeholder="请输入手机号"
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="验证码" prop="captchaCode">
                <el-input
                  v-model="phoneLoginDTO.captchaCode"
                  clearable
                  placeholder="请输入验证码"
                  @keyup.enter="phoneLoginSubmit"
                >
                  <template #append>
                    <el-button
                      :disabled="phoneCountdown !== 60"
                      style="width: 150px"
                      @click="sendPhoneCode"
                      >{{ phoneSubText }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-form
          v-show="active === 2"
          ref="updatePwdRef"
          :model="updatePwdData"
          :rules="pwdRules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="updatePwdData.newPassword"
                  clearable
                  placeholder="请输入新的密码"
                  show-password
                  type="password"
                />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="updatePwdData.confirmPassword"
                  clearable
                  placeholder="请再次输入新的密码"
                  show-password
                  type="password"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-scrollbar>
    <!-- 弹窗底部操作按钮 -->
    <template #footer>
      <div v-if="active == 0">
        <el-button type="primary" @click="active++">继 续</el-button>
        <el-button @click="forgetVisible = false">取 消</el-button>
      </div>
      <div v-if="active == 1">
        <el-button type="success" @click="active--">返 回</el-button>
        <el-button type="primary" @click="active++">继 续</el-button>
      </div>
      <div v-if="active == 2">
        <el-button type="success" @click="active--">返 回</el-button>
        <el-button type="primary" @click="active++">提 交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
// 外部库和依赖
import { LocationQuery, useRoute } from "vue-router";
import { onUnmounted, reactive, ref } from "vue";
import router from "@/router";
import LOGO from "@/assets/logo.png";
import LOGO_LEFT from "@/assets/img.png";
// 类型定义
import type { TabsPaneContext } from "element-plus";
import { ElMessage } from "element-plus";
import {
  BasicControllerService,
  EmailLoginDTO,
  LoginDTO,
  PhoneLoginDTO,
  UpdatePasswordDTO,
  UserInfoControllerService,
} from "@/api";
import { useUserStore } from "@/store";
import CaptchaInput from "@/components/CaptchaInput.vue";

const userStore = useUserStore();

enum PaneEnum {
  USERNAME = "账号登录",
  EMAIL = "邮箱验证登录",
  PHONE = "手机号验证登录",
}

function handleTabClick(pane: TabsPaneContext) {
  if (pane.props.label === PaneEnum.USERNAME) {
    loginRef.value[0].resetFields();
  } else if (pane.props.label === PaneEnum.EMAIL) {
    emailLoginRef.value[0].resetFields();
  } else {
    phoneLoginRef.value[0].resetFields();
  }
}

//账号登录开始
//获取验证码数据
function handleCaptchaData(data: any, enterFlag?: boolean) {
  loginData.value.captchaKey = data.captchaKey;
  loginData.value.captchaCode = data.captchaCode;
  //回车键，直接调用提交事件
  if (enterFlag) {
    loginSubmit();
  }
}

//用户类型选项
const options = [
  {
    label: "用户",
    value: 0,
  },
  {
    label: "商家",
    value: 1,
  },
  {
    label: "管理员",
    value: 2,
  },
];
const loginRef = ref();
// 表单规则
const loginRules = reactive({
  username: [
    {
      required: true,
      trigger: "blur",
      message: "请填入用户名",
    },
  ],
  password: [
    {
      required: true,
      trigger: "blur",
      message: "请输入密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
  ],
  captchaCode: [
    {
      required: true,
      trigger: "blur",
      message: "请输入验证码",
    },
  ],
});
const loginData = ref<LoginDTO>({
  userType: 2,
  username: "admin01",
  password: "12345678",
});

function loginSubmit() {
  loginRef.value[0].validate((valid: boolean) => {
    if (valid) {
      BasicControllerService.loginUsingPost(loginData.value).then((res) => {
        //跳转到重定向页面或者首页
        toRedirect(res.data);
      });
    }
  });
}

// 邮箱验证开始
const emailLoginRef = ref();
// 表单规则
const emailLoginRules = {
  email: [
    {
      required: true,
      trigger: "blur",
      message: "请输入邮箱",
    },
    {
      type: "email",
      trigger: "blur",
      message: "邮箱格式不对，请重新输入",
    },
  ],
  captchaCode: [
    {
      required: true,
      trigger: "blur",
      message: "请输入验证码",
    },
    {
      len: 6,
      message: "请输入6位验证码",
      trigger: "blur",
    },
  ],
};
const emailLoginDTO = ref<EmailLoginDTO>({});
const emailSubText = ref("获取邮箱验证码");
const emailCountdown = ref(60); //倒计时统计
const emailInterval = ref(); // 计时器
function sendEmailCode() {
  //验证邮箱格式
  emailLoginRef.value[0].validateField("email", (validate: boolean) => {
    if (validate) {
      if (emailCountdown.value === 60) {
        //发送验证码
        BasicControllerService.sendEmailCodeUsingGet(
          emailLoginDTO.value.email
        ).then((res) => {
          ElMessage.success(res.data);
        });
        emailInterval.value = setInterval(() => {
          console.log("倒计时了", emailCountdown);
          emailCountdown.value--;
          emailSubText.value = emailCountdown.value + "秒后重新获取";
          if (emailCountdown.value === 1) {
            emailCountdown.value = 60;
            emailSubText.value = "获取邮箱验证码";
            clearInterval(emailInterval.value);
          }
        }, 1000);
      }
    }
  });
}

function emailLoginSubmit() {
  emailLoginRef.value[0].validate((valid: boolean) => {
    if (valid) {
      BasicControllerService.emailLoginUsingPost(emailLoginDTO.value).then(
        (res) => {
          //跳转到重定向页面或者首页
          toRedirect(res.data);
        }
      );
    }
  });
}

// 手机验证开始
const phoneLoginRef = ref();
// 表单规则
const phoneLoginRules = {
  phone: [
    {
      required: true,
      trigger: "blur",
      message: "请输入手机号",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确",
      trigger: "blur",
    },
  ],
  captchaCode: [
    {
      required: true,
      trigger: "blur",
      message: "请输入验证码",
    },
    {
      len: 6,
      message: "请输入6位验证码",
      trigger: "blur",
    },
  ],
};
const phoneLoginDTO = ref<PhoneLoginDTO>({});
const phoneSubText = ref("获取手机验证码");
const phoneCountdown = ref(60); //倒计时统计
const phoneInterval = ref(); // 计时器
function sendPhoneCode() {
  //验证邮箱格式
  phoneLoginRef.value[0].validateField("phone", (validate: boolean) => {
    if (validate) {
      if (phoneCountdown.value === 60) {
        //发送验证码
        BasicControllerService.sendPhoneCodeUsingGet(
          phoneLoginDTO.value.phone as string
        ).then((res) => {
          ElMessage.success(res.data);
        });
        phoneInterval.value = setInterval(() => {
          phoneCountdown.value--;
          phoneSubText.value = phoneCountdown.value + "秒后重新获取";
          if (phoneCountdown.value === 1) {
            phoneCountdown.value = 60;
            phoneSubText.value = "获取手机验证码";
            clearInterval(phoneInterval.value);
          }
        }, 1000);
      }
    }
  });
}

function phoneLoginSubmit() {
  phoneLoginRef.value[0].validate((valid: boolean) => {
    if (valid) {
      BasicControllerService.phoneLoginUsingPost(phoneLoginDTO.value).then(
        (res) => {
          //跳转到重定向页面或者首页
          toRedirect(res.data);
        }
      );
    }
  });
}

const route = useRoute();

//跳转到重定向页面
function toRedirect(token: string) {
  //设置token
  userStore.setToken(token);
  ElMessage.success("登录成功！");

  // 获取路径参数
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  //转换为地址
  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};
  // 设置路径参数
  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });
  router.replace({
    path: path,
    query: queryParams,
  });
}

const toRegister = (type: string) => {
  router.push({
    path: "/basic/register",
    query: { type },
  });
};

// 忘记密码
const forgetVisible = ref(false);

// 打开忘记弹窗
function openForget() {
  forgetVisible.value = true;
}

//选项
const active = ref(0);

const updatePwdData = ref<UpdatePasswordDTO>({});
const updatePwdVisible = ref(false);
const updatePwdRef = ref();

//二次密码确认校验
function validatePwd(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请再次输入密码"));
    return;
  }
  if (value !== updatePwdData.value.newPassword) {
    callback(new Error("两次密码不一致"));
    return;
  }
  callback();
}

//规则
const pwdRules = {
  newPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请输入新的密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请再次输入密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
    { validator: validatePwd, trigger: "blur" },
  ],
};

// 修改密码提交
function updatePwdSubmit() {
  updatePwdRef.value.validate((validate: boolean) => {
    if (validate) {
      UserInfoControllerService.updateUserInfoSelfPwdUsingPut(
        updatePwdData.value
      ).then((res) => {
        ElMessage.success(res.data);
        active.value = 0;
      });
    }
  });
}

onUnmounted(() => {
  clearInterval(emailInterval.value);
  clearInterval(phoneInterval.value);
});
</script>

<style lang="scss" scoped>
#loginPage {
  background: linear-gradient(to bottom right, #ead6ee, #a0f1ea);
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;

  .main {
    margin: 0 auto;
    width: 60%;
    display: flex;
    border-radius: 16px;
    overflow: hidden;

    .main-left {
      flex: 1;
    }

    .login-tabs {
      flex: 1;

      .logo {
        display: flex;
        place-content: center center;
        width: 100%;
        height: 50px;
        padding: 10px;

        & span {
          display: block;
          margin: auto 10px;
          font-size: 24px;
          font-weight: bold;
        }
      }

      .link {
        margin-top: 10px;
        float: left;

        &:last-child {
          float: right;
        }
      }
    }
  }

  .icp-info {
    left: 40%;
    bottom: 10px;
    position: absolute;
  }
}

:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0 !important;
  margin: auto 0;
  background-color: #409eff;
  color: white;
}

:deep(.el-tabs__content) {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.text-sm {
  text-align: right;

  &:hover {
    color: #20a0ff;
  }
}
</style>
